<!DOCTYPE html>
<html>

<?php
	session_start();
	
		//Conexión a la bd
		$link = mysqli_connect('localhost', 'root', '') or die("Failed to connect to MySQL: " . mysql_error());
		if (mysqli_connect_errno()) {
		        echo 'Failed to connect to MySQL';
		        exit;
		}
		$sql = "USE web_db";
		$query = mysqli_query($link,$sql);

	if(isset($_SESSION['id'], $_SESSION['vorname'], $_SESSION['name'])){
		$id = $_SESSION['id'];
		$vorname = $_SESSION['vorname'];
		$name = $_SESSION['name'];
		$b_date = $_SESSION['b_date'];
		$location = $_SESSION['location'];
	}else{
		header("location:index.php");
	}

	//Carga las misiones de un piloto
	function load_mis(){
		global $link;
		global $id;

		$sql = "SELECT mi.name, mi.description, mi.status, mi.miss_nr
				FROM mission mi, mech_mission mm, mecha me
				WHERE me.id = '$id' AND me.mec_id = mm.mec_id AND mm.mission_nr = mi.miss_nr";
		$query = mysqli_query($link,$sql);

		$num = mysqli_num_rows($query);

		if($num == 0){
			echo "Waiting for a personal mission to be asigned...";
		}

		echo "<table>";
		echo "<tr><td colspan='2'><hr></td></tr>";
		while($row = mysqli_fetch_row($query)){
			//Consultar paises de la mision
			$sql = "SELECT c.name
					FROM country c, country_mission cm
					WHERE '$row[3]'= cm.mission_nr AND c.code = cm.code";
			$aux = mysqli_query($link,$sql);

			echo "<tr>";
			echo "<td><h2>Mission name: " . $row[0] . "</h2>Country: ";
			while($country = mysqli_fetch_row($aux)){
				echo $country[0].", ";
			}
			echo "</td><td style=text-align:center>Status: " . $row[2] . "<br>";
			echo "</tr>";
			echo "<tr><td colspan='2'>Description: <br>" . $row[1] . "</td></tr>";
			echo "<tr><td colspan='2'><hr></td></tr>";
		}
		echo "</table>";
	}

	//Carga todas las misiones
	function load_all(){
		global $link;

		//Version que enseña sólo una misión, aunque esté asignada a más de un piloto
		$sql = "SELECT miss_nr ,name, description, status
				FROM mission";
		$query = mysqli_query($link,$sql);

		echo "<table>";
		while($row = mysqli_fetch_row($query)){

			//Consultar participantes de la mision
			$sql = "SELECT st.vorname, st.name
					FROM staff st, mecha me, mech_mission mm
					WHERE '$row[0]'= mm.mission_nr AND mm.mec_id = me.mec_id AND me.id = st.id";
			$con = mysqli_query($link,$sql);

			//Consultar paises de la mision
			$sql = "SELECT c.name
					FROM country c, country_mission cm
					WHERE '$row[0]'= cm.mission_nr AND c.code = cm.code";
			$aux = mysqli_query($link,$sql);

			echo "<tr>";
			echo "<td><h2>Mission name: " . $row[1] . "</h2>Country: ";
			while($country = mysqli_fetch_row($aux)){
				echo $country[0].", ";
			}
			echo "</td><td style=text-align:center>Status: " . $row[3] . "<br>";
			if($row[3] != "Completed"){
				echo "<form method=\"POST\" action=\"set_complete.php\">";
				echo "<input type=\"hidden\" name=\"miss_nr\" value=" . $row[0] . ">";
				echo "<input type=\"submit\" name=\"submit\" value=\"Set complete\">";
				echo "</form>";
			}
			//Crea el boton de borrar
			echo "<form method=\"POST\" action=\"del_mission.php\">";
			echo "<input type=\"hidden\" name=\"miss_nr\" value=" . $row[0] . ">";
			echo "<input type=\"submit\" name=\"submit\" value=\"Delete\">";
			echo "</form>";

			echo "</td>";
			echo "</tr>";
			echo "<tr><td>Description: <br><p id=\"" . $row[0] . "\">" . $row[2] . "</p></td>";

			//Se añaden todos los pilotos asignados a la mision
			echo "</p></td><td style=text-align:center>Asigned to: <br>";
			while($name = mysqli_fetch_row($con)){
				echo $name[1] . ", " . $name[0] . "<br>";
			}
			echo "</td>";

			echo "</tr>";
			echo "<tr><td><hr></td></tr>";
		}
		echo "</table>";
	}

	function load_pilots($prev = "noexists"){
		$pilots_list = $_SESSION['pilots_list'];
		global $link;

		$sql = "SELECT st.vorname, st.name, me.mec_id, st.id
				FROM staff st, mecha me
				WHERE st.id = me.id";
		$query = mysqli_query($link,$sql);

		//Añade el piloto recibido a la lista de elegidos
		if($prev != "noexists"){
			$pilots_list[$prev] = "yes";
		}

		while($row = mysqli_fetch_row($query)){
			if(array_key_exists($row[2], $pilots_list)){
				//Ya se ha elegido ese piloto
				//echo "Mecha " . $row[2] . " elegido.<br>";
			}else{
				echo "<option value=\"" . $row[2] . "\">" . $row[2] . " - " . $row[1] . ", " . $row[0] . "</option>";
			}
		}
	}

	function num_pilots(){
		global $link;

		$sql = "SELECT COUNT( * ) cuenta
				FROM mecha";
		$query = mysqli_query($link,$sql);
		$row = mysqli_fetch_row($query);

		echo $row[0];
	}

	function load_country(){
		global $link;

		$sql = "SELECT code, name
				FROM country";
		$query = mysqli_query($link,$sql);

		
		while($row = mysqli_fetch_row($query)){
			echo "<option value=\"" . $row[0] . "\">" . $row[0] . " - " . $row[1] . "</option>";
		}
	}
?>

<head>

<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./css/index.css">
<link href='./images/favicon.ico' rel='shortcut icon' type='image/png'>
<title>Missions</title>
</head>

<body id="fondo">
	<div id="cuerpo">
	<fieldset style="width: 1000px color: #FFF">
		<?php
			include 'header.php';
		?>
		<div id="subcuerpo">
			<h2>Personal missions</h2>
		<?php
			//Carga misiones de la plebe
			load_mis();

			//Carga todas las misiones
			if($_SESSION['workstation'] >= 8){
				echo "<hr>";
				echo "<h2>All missions</h2>";
				load_all();
			}
		?>

		<?php if($_SESSION['workstation'] >= 8) : ?>
		<h3><a href="javascript:add()">Add mission</a></h3>
		<form method="POST" action="add_mission.php">
		<table id="t_add" style="visibility:hidden">
			<tr> <td>Name:</td> <td><input type="text" name="name"></td> </tr>
			<tr> <td>Description:</td> <td><textarea name="desc" cols="40" rows="5"></textarea></td> </tr>
			<tr> <td>Country:</td> <td><select id="country" name="country"> <?php load_country();?> </select></td> </tr>
			<tr> <td>Assign to:</td> <td> <input type="hidden" value="1" id="num_pilots" name="num_pilots"/>

				<table id="pilots"><tr><td> <select id="mec_id0" name="mec_id0"> <?php load_pilots();?> </select> </td></tr></table></td>
															 
															 <td><img src="images/add.png" id="mas" onclick="add_pilot()">
													<img src="images/minus_red.png" id="minus" style="visibility:hidden" onclick="del_pilot()"></td> </tr>
			<tr> <td></td> <td><input type="submit" name="submit" onclick="activate()" value="Save"></td> </tr>
		</table>
		</form>
		<?php endif; ?>
		</div>
	<?php
		include 'footer.php';
	?>
	</div>
</body>

<script type="text/javascript">

var editing  = false;

if (document.getElementById && document.createElement) {
	var butt = document.createElement('BUTTON');
	var buttext = document.createTextNode('Save');
	butt.appendChild(buttext);
	butt.onclick = saveEdit;
}

function catchIt(e) {
	if (editing) return;
	if (!document.getElementById || !document.createElement) return;
	if (!e) var obj = window.event.srcElement;
	else var obj = e.target;
	while (obj.nodeType != 1) {
		obj = obj.parentNode;
	}
	if (obj.tagName == 'TEXTAREA' || obj.tagName == 'A') return;
	while (obj.nodeName != 'P' && obj.nodeName != 'HTML') {
		obj = obj.parentNode;
	}
	if (obj.nodeName == 'HTML') return;
	var x = obj.innerHTML;
	var ide = obj.id;
	var y = document.createElement('TEXTAREA');
	var z = obj.parentNode;
	z.insertBefore(y,obj);
	z.insertBefore(butt,obj);
	z.removeChild(obj);
	y.value = x;
	y.id = ide;
	y.focus();
	editing = true;
}

function saveEdit() {
	var area = document.getElementsByTagName('TEXTAREA')[0];
	var y = document.createElement('P');
	var z = area.parentNode;
	y.innerHTML = area.value;
	z.insertBefore(y,area);
	z.removeChild(area);
	z.removeChild(document.getElementsByTagName('button')[0]);
	editing = false;
	post_to_url('update_mission.php', {'desc': y.innerHTML, 'mision':area.id});
}

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

function add(){
	var elem = document.getElementById("t_add");
	
	if(elem.style.visibility=="visible"){
		elem.style.visibility="hidden";
	}else{
		elem.style.visibility="visible";
	}
}

function add_pilot(){
	document.getElementById('minus').style.visibility = "visible";

	var tabla = document.getElementById('pilots');
	var num = (document.getElementById('num_pilots').value -1) +1; //Hay que hacer esto para que lo pille como entero
	document.getElementById('num_pilots').value = num + 1;
	var newselect = document.createElement('select');
	var ide = 'mec_id' + num;
	var pilotos = parseInt("<?php num_pilots() ?>");

	newselect.setAttribute('id', ide);
	newselect.setAttribute('name', ide);

	//Deshabilita el select anterior
	var old = 'mec_id' + (num - 1);
	document.getElementById(old).disabled = true;

	var x = document.getElementById(old).selectedIndex;
	var y = document.getElementById(old).options;

	var valor = y[x].value; //Saca el valor de la anterior elección
	
	var xmlhttp;
	xmlhttp=new XMLHttpRequest();

	xmlhttp.onreadystatechange=function()
	 {
	 	if (xmlhttp.readyState==4 && xmlhttp.status==200){
	 		var num = (document.getElementById('num_pilots').value -1) +1;
	 		var ide = 'mec_id' + (num-1);

	 		document.getElementById(ide).innerHTML=xmlhttp.responseText;
	 	}
	 }

	xmlhttp.open("GET","showpilots.php?id="+valor+"&modo=carga",true);
	xmlhttp.send();

	var row = tabla.insertRow(num);
	var cell1 = row.insertCell(0);

	cell1.appendChild(newselect);

	//Si no se pueden poner más pilotos, desaparece el más
	if(num+1 == pilotos){
		document.getElementById('mas').style.visibility = "hidden";
	}
}

function del_pilot(){
	var tabla = document.getElementById('pilots');
	var num = (document.getElementById('num_pilots').value -1) +1;
	document.getElementById('num_pilots').value = num - 1;
	tabla.deleteRow(num - 1);
	var pilotos = parseInt("<?php num_pilots() ?>");

	if(num == 2){
		document.getElementById('minus').style.visibility = "hidden";
	}
	if(num < pilotos+1){
		document.getElementById('mas').style.visibility = "visible";
	}

	//Habilita el select anterior
	var old = 'mec_id' + (num - 2);
	document.getElementById(old).disabled = false;

	//Borrar el piloto de antes para que pueda volver a aparecer
	var x = document.getElementById(old).selectedIndex;
	var y = document.getElementById(old).options;

	var valor = y[x].value; //Saca el valor de la anterior elección

	var xmlhttp;
	xmlhttp=new XMLHttpRequest();

	xmlhttp.open("GET","showpilots.php?id="+valor+"&modo=del",true);
	xmlhttp.send();
}

//Pone en enabled todos los selects
function activate(){
	var num = (document.getElementById('num_pilots').value -1) +1;

	while(num != 0){
		var act = 'mec_id' + (num - 1);
		document.getElementById(act).disabled = false;
		num = num -1;
	}
}

document.onclick = catchIt;
</script>

</html>